package middlewares

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// CORS 处理跨域请求的中间件
func CORS() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 允许的源
		allowedOrigins := []string{"http://localhost:3000", "http://127.0.0.1:3000"} // 前端开发服务器地址
		origin := c.Request.Header.Get("Origin")

		// 检查请求源是否在允许列表中
		if origin != "" {
			for _, allowed := range allowedOrigins {
				if origin == allowed {
					c.Header("Access-Control-Allow-Origin", origin)
					break
				}
			}
		} else {
			// 非跨域请求（如同一域名），允许访问
			c.Header("Access-Control-Allow-Origin", "*")
		}

		// 允许的请求方法
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")

		// 允许的请求头
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, X-Requested-With")

		// 允许前端读取的响应头
		c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type")

		// 允许携带凭证（如 cookies）
		c.Header("Access-Control-Allow-Credentials", "true")

		// 预检请求（OPTIONS）处理
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent) // 204 No Content
			return
		}

		// 继续处理请求
		c.Next()
	}
}
